{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python介绍\n",
    "\n",
    "> *python* 是你不去认识它，可能没什么，一旦你认识了它，你就会爱上它\n",
    "\n",
    "Python（英语发音：/ˈpaɪθən/）,\n",
    "是一种面向对象、解释型计算机程序设计语言，由Guido van Rossum于1989年发明，第一个公开发行版发行于1991年。\n",
    "Python是纯粹的自由软件，\n",
    "源代码和解释器CPython遵循 GPL(GNU General Public License)协议。\n",
    "Python语法简洁清晰，特色之一是强制用空白符(white space)作为语句缩进。\n",
    "Python具有丰富和强大的库。它常被昵称为胶水语言，能够把用其他语言制作的各种模块（尤其是C/C++）很轻松地联结在一起。常见的一种应用情形是，使用Python快速生成程序的原型（有时甚至是程序的最终界面），然后对其中有特别要求的部分，用更合适的语言改写，比如3D游戏中的图形渲染模块，性能要求特别高，就可以用C/C++重写，而后封装为Python可以调用的扩展类库。需要注意的是在您使用扩展类库时可能需要考虑平台问题，某些可能不提供跨平台的实现。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## Python开发环境\n",
    "\n",
    "### Python运行环境\n",
    "\n",
    "- Python基础运行环境只需要到python的官网（[ttps://www.python.org/](https://www.python.org/)）下载相应的安装文件即可.\n",
    "- 安装完成之后需要将python的安装路径添加到系统的path环境变量中。\n",
    "- 官方的python安装环境只包含有基本的运行环境和基础的软件包，功能比较少。\n",
    "- Python强大的地方就在于python可以找到极其多的功能包或模块。\n",
    "要利用Python进行科学计算，就需要一一安装所需的模块，而这些模块可能又依赖于其它的软件包或库，因而安装和使用起来相对麻烦。\n",
    "\n",
    "- 幸好有人专门在做这一类事情，将科学计算所需要的模块都编译好，然后打包以发行版的形式供用户使用，Anaconda就是其中一个常用的科学计算发行版。\n",
    "下载网址：[https://www.anaconda.com/download/#windows](https://www.anaconda.com/download/#windows)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "### Python IDE\n",
    "\n",
    "优秀的Python IDE有很多，这里我就介绍几款相对我来说比较常用的！\n",
    "\n",
    "- VS Code\n",
    "- pycharm\n",
    "- Atom\n",
    "- Sublime Text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python运行方式\n",
    "\n",
    "### Python交互式编程\n",
    "\n",
    "- 交互式编程不需要创建脚本文件，是通过Python 解释器的交互模式进来编写代码。\n",
    "\n",
    "- 只需要在命令行中输入 Python 命令即可启动交互式编程\b窗口。\n",
    "\n",
    "- 在 python 命令提示符中输入以下文本信息，然后按 Enter 键查看运行效果：\n",
    "\n",
    "$$E = mc^2$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, world! Hello Python!\n"
     ]
    }
   ],
   "source": [
    "print(\"Hello, world! Hello Python!\")\n",
    "1+1\n",
    "x = 1\n",
    "y = 1 \n",
    "z = x+y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "### Python脚本式编程\n",
    "\n",
    "通过脚本参数调用解释器开始执行脚本，直到脚本执行完毕。当脚本执行完成后，解释器不再有效。\n",
    "\n",
    "所有 Python 文件将以.py 为扩展名，例如将上面的print代码放到test.py文件中。\n",
    "\n",
    "假设你已经设置了Python解释器 的 PATH 变量。使用以下命令运行程序：\n",
    "让我们写一个简单的 Python 脚本程序, test.py。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "C\n"
     ]
    }
   ],
   "source": [
    "def main():\n",
    "    score = int(input(\"Please input your score : \"))\n",
    "    if 90 <= score <= 100:\n",
    "        print('A')\n",
    "    elif score >= 80:\n",
    "        print('B')\n",
    "    elif score >= 70:\n",
    "        print('C')\n",
    "    elif score >= 60:\n",
    "        print('D')\n",
    "    else:\n",
    "        print('Your score is too low')\n",
    "\n",
    "main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8\n"
     ]
    }
   ],
   "source": [
    "def add(x, y):\n",
    "    \"\"\"\n",
    "    x: 加数\n",
    "    y: 被加数\n",
    "    return: 和\n",
    "    comments\n",
    "    comments\n",
    "    \"\"\"\n",
    "\n",
    "    return x + y\n",
    "\n",
    "def add2(x, y):\n",
    "    return x * 2 + y * 2\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    z = add(3, 5)\n",
    "    print(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{.python .input .dos}\n",
    "python test.py\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "- 标准的python脚本文件\n",
    " <img src=\"figures/pythonintro.jpg\" width = \"600\" alt=\"python\n",
    "脚本介绍\" align=center />\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## Python基础语法\n",
    "\n",
    "### 行和缩进\n",
    "- 一个程序员学习Python时，遇到的第一个需要注意的地方是，不使用括号来表示代码的类和函数定义块或流程控制。代码块是由行缩进，这是严格执行表示方式。\n",
    "\n",
    "- 在缩进位的数目是可变的，但是在块中的所有语句必须缩进相同的量。\n",
    "\n",
    "- python推荐使用4个空格或者tab键作为缩进。\n",
    "\n",
    "\n",
    "### 标识符\n",
    "- 第一个字符必须是字母表中字母或下划线'_'。\n",
    "- 标识符的其他的部分由字母、数字和下划线组成。\n",
    "- 标识符对大小写敏感。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "### python的保留字\n",
    "\n",
    "```python\n",
    "'False','None','True','and','as','assert','break','class','continue','def','del', \n",
    "'elif','else','except','finally','for','from','global','if','import','in','is','lambda',\n",
    "'nonlocal','not','or','pass','raise','return','try','while','with','yield'\n",
    "```\n",
    "\n",
    "### 注释\n",
    "\n",
    "```python\n",
    "Python中单行注释以 '#' 开头，实例如下：\n",
    "#!/usr/bin/python3\n",
    "# 第一个注释 \n",
    "print(\"Hello,Python!\")\n",
    "# 第二个注释 执行以上代码，输出结果为：Hello,Python! \n",
    "# 多行注释可以用多个#号：\n",
    "# !/usr/bin/python3\n",
    "# 第一个注释\n",
    "# 第二个注释 \n",
    "print(\"Hello,Python!\")\n",
    "# 执行以上代码，输出结果为：Hello,Python!\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 定义变量：\n",
    "\n",
    "- Python 直接在赋值的时候定义变量\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "x=1\n",
    "y=2\n",
    "z=x+y\n",
    "c = 3\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "- Python中的变量不需要声明。每个变量在使用前都必须赋值，变量赋值以后该变量才会被创建\n",
    "\n",
    "- Python3支持int、float、bool、complex（复数）。\n",
    "\n",
    "- 在 Python中，变量就是变量，它没有类型，我们所说的\"类型\"是变量所指的内存中对象的类型。\n",
    "    - 等号（=）用来给变量赋值。\n",
    "    - 等号（=）运算符左边是一个变量名,等号（=）运算符右边是存储在变量- 中的值。\n",
    "    - 一个变量可以通过赋值指向不同类型的对象。\n",
    "    - 数值的除法（/）总是返回一个浮点数，要获取整数使用//操作符。\n",
    "    - 在混合计算时，Python会把整型转换成为浮点数。\n",
    "\n",
    "代码示例：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100\n",
      "1000.0\n",
      "2 1\n"
     ]
    }
   ],
   "source": [
    "counter = 100      # 整型变量\n",
    "miles = 1000.0       # 浮点型变量\n",
    "print (counter)\n",
    "print (miles)\n",
    "\n",
    "a = b = c = 1  # 多个变量赋值\n",
    "a, b = 1, 2  # Python可以同时为多个变量赋值\n",
    "a, b = b, a\n",
    "print(a, b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "**现在在国外很多大学都是把Python作为计算机语言入门的第一门语言，因为python语言可以说是人类的语言，很容易上手，一眼就能看懂**\n",
    "\n",
    "**不过大部分语言都是这样，入门容易精通难，要持之以恒。**\n",
    "\n",
    "### 字符串\n",
    "- python中的字符串str用单引号(' ')或双引号(\" \")括起来，同时使用反斜杠(\\)转义特殊字符\n",
    "\n",
    "- 字符串可以使用 +\n",
    "运算符串连接在一起，或者用 * 运算符重复\n",
    "\n",
    "- 使用三引号('''...'''或\"\"\"...\"\"\")可以指定一个多行字符串\n",
    "\n",
    "- 如果不想让反斜杠发生转义，可以在字符串前面添加一个 r 或 R, 表示原始字符串。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ice cream\n",
      "ice cream ice cream ice cream \n",
      "呵呵\n",
      "          呵呵呵\n",
      "          呵呵呵呵\n",
      "ice        cream\n",
      "this is a line with \\n\n"
     ]
    }
   ],
   "source": [
    "text = 'ice'+' cream'\n",
    "print(text)\n",
    "\n",
    "text = 'ice cream '*3\n",
    "print(text)\n",
    "\n",
    "text = '''呵呵\n",
    "          呵呵呵\n",
    "          呵呵呵呵'''\n",
    "\n",
    "print(text)\n",
    "text = 'ice\\\n",
    "        cream'\n",
    "print(text)\n",
    "\n",
    "print(r\"this is a line with \\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "- 字符串有两种索引方式，第一种是从左往右，从0开始依次增加；第二种是从右往左，从-1开始依次减少。\n",
    "\n",
    "- python中没有单独的字符类型，一个字符就是长度为1的字符串\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9\n",
      "i\n",
      "i\n",
      "m\n",
      "m\n"
     ]
    }
   ],
   "source": [
    "text = 'ice cream'\n",
    "print(len(text))\n",
    "\n",
    "print(text[0])  # i\n",
    "print(text[-9])  # i\n",
    "\n",
    "print(text[8])  # m\n",
    "print(text[-1])  # m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "- python字符串不能被改变。向一个索引位置赋值会导致错误\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ice cream\n",
      "ce c\n"
     ]
    }
   ],
   "source": [
    "text = 'ice cream'\n",
    "# text[0] = 't'  # 报错\n",
    "print(text) \n",
    "print(text[1:5])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "- 还可以对字符串进行切片，获取一段子串。用冒号分隔两个索引，形式为变量[头下标 : 尾下标]。\n",
    "- 截取的范围是前闭后开的，并且两个索引都可以省略\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "### 分支\n",
    "- if-else 语句与其他语言类似，不再赘述\n",
    "\n",
    "- if-elif-else 语句，相当于c或java语言中的if-else if-else\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your score is too low\n"
     ]
    }
   ],
   "source": [
    "while True:\n",
    "    score = int(input(\"Please input your score : \"))\n",
    "    if 90 <= score <= 100:\n",
    "        print('A')\n",
    "    elif score >= 80:\n",
    "        print('B')\n",
    "    elif score >= 70:\n",
    "        print('C')\n",
    "    elif score >= 60:\n",
    "        print('D')\n",
    "    else:\n",
    "        print('Your score is too low')\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "### 循环\n",
    "\n",
    "while循环语句一般形式：\n",
    "\n",
    "```python\n",
    "while 判断条件：\n",
    "    statement\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "wrong...\n",
      "required a smaller number\n",
      "yes...\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "number = random.randint(1, 10)\n",
    "temp = input(\"Please input a number : \")\n",
    "i = int(temp)\n",
    "\n",
    "while i != number:\n",
    "    print(\"wrong...\")\n",
    "    if i < number:\n",
    "        print(\"required a bigger number\")\n",
    "    else:\n",
    "        print(\"required a smaller number\")\n",
    "    temp = input(\"Please input a number : \")\n",
    "    i = int(temp)\n",
    "\n",
    "print(\"yes...\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "for循环的一般格式如下：\n",
    "\n",
    "```python\n",
    "for <variable> in <sequence>:\n",
    "　　<statements>\n",
    "else:\n",
    "　　<statements>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "C 1\n",
      "c++ 3\n",
      "java 4\n",
      "python 6\n"
     ]
    }
   ],
   "source": [
    "languaegs = ['C', 'c++', 'java', 'python']\n",
    "for language in languaegs:\n",
    "    print(language, len(language))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "> 循环语句可以有else子句\n",
    "它在穷尽列表(以for循环)或条件变为假(以while循环)循环终止时被执行\n",
    "但循环被break终止时不执行.\n",
    "如下查寻质数的循环例子:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "2 is a prime number\n",
      "3\n",
      "2\n",
      "3 is a prime number\n",
      "4\n",
      "2\n",
      "4 equals 2 * 2\n",
      "5\n",
      "2\n",
      "3\n",
      "4\n",
      "5 is a prime number\n",
      "6\n",
      "2\n",
      "6 equals 2 * 3\n",
      "7\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n",
      "6\n",
      "7 is a prime number\n",
      "8\n",
      "2\n",
      "8 equals 2 * 4\n",
      "9\n",
      "2\n",
      "3\n",
      "9 equals 3 * 3\n"
     ]
    }
   ],
   "source": [
    "for num in range(2, 10):\n",
    "    for x in range(2, num):\n",
    "        if num%x == 0:\n",
    "            print(num, 'equals', x, '*', num//x)\n",
    "            break\n",
    "    else:\n",
    "        # 循环中没有找到元素\n",
    "        print(num, 'is a prime number')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "> 如果需要遍历数字序列，可以使用内置range()函数：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n"
     ]
    }
   ],
   "source": [
    "x = range(2, 2)\n",
    "print(len(x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# range()函数,含头不含尾\n",
    "# 0~4\n",
    "for i in range(5):\n",
    "    print(i)\n",
    "\n",
    "# 2~7\n",
    "for i in range(2, 8):\n",
    "    print(i)\n",
    "\n",
    "# 1~9 步长为3\n",
    "for i in range(1, 10, 3):\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python科学计算\n",
    "Python专用的科学计算扩展库有很多，例如三个十分经典的科学计算扩展库：NumPy、SciPy和matplotlib，它们分别为Python提供了快速数组处理、数值运算以及绘图等功能。因此Python语言十分适合工程技术、科研人员处理实验数据，制作图表，甚至开发科学计算应用程序。\n",
    "### numpy\n",
    " NumPy(Numerical Python) 是 Python\n",
    "语言的一个扩展程序库，支持大量的维度数组与矩阵运算，此外也针对数组运算提供大量的数学函数库。\n",
    "\n",
    "NumPy 的前身 Numeric 最早是由 Jim\n",
    "Hugunin 与其它协作者共同开发，2005 年，Travis Oliphant 在 Numeric 中结合了另一个同性质的程序库 Numarray\n",
    "的特色，并加入了其它扩展而开发了 NumPy。NumPy 为开放源代码并且由许多协作者共同维护开发。\n",
    "\n",
    "NumPy 是一个运行速度非常快的数学库，主要用于数组计算，线性代数、傅里叶变换、随机数生成等功能\n",
    "\n",
    "NumPy 通常与 SciPy（Scientific Python）和\n",
    "Matplotlib（绘图库）一起使用， 这种组合广泛用于替代 MatLab，是一个强大的科学计算环境，有助于我们通过 Python 学习数据科学或者机器学习。\n",
    "\n",
    "[Numpy官网](https://numpy.org)\n",
    "\n",
    "![numpy](figures/numpy.png)\n",
    "\n",
    "\n",
    "> 2020年，NumPy 核心开发团队的论文终于在 Nature 上发表，详细介绍了使用 NumPy 的数组编程（Array programming）。这篇综述论文的发表距离 NumPy 诞生已经过去了 15 年。\n",
    "> 这篇论文的核心内容：\n",
    "NumPy 为数组编程提供了简明易懂、表达力强的高级 API，同时还考虑了维持快速运算的底层机制。\n",
    "NumPy 提供的数组编程基础和生态系统中的大量工具结合，形成了适合探索性数据分析的完美交互环境。NumPy 还包括增强与 PyTorch、Dask 和 JAX 等外部库互操作性的协议。\n",
    "基于这些特性，NumPy 为张量计算提供了标准的 API，成为 Python 中不同数组技术之间的核心协调机制。\n",
    "\n",
    "![numpynature](figures/numpynature.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "#### Numpy examples\n",
    "参考Numpy Jupyter Notebook\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入numpy的几种方法\n",
    "import numpy\n",
    "import numpy as np\n",
    "from numpy import *\n",
    "from numpy import array, sin"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- scipy\n",
    "  \n",
    "![scipy](figures/scipy.png)\n",
    "\n",
    "### Scipy examples\n",
    "参考Scipy Jupyter Notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- matplotlib\n",
    "  \n",
    "![numpy](figures/matplotlib.png)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### matplotlib example\n",
    "参考Matplotlib jupyter notebook\n"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "0ba00dd77806596ecbc07d55b4ddf41b2ae8cecbf91d9534027e74a33368b668"
  },
  "kernelspec": {
   "display_name": "Python 3.8.3 64-bit ('base': conda)",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
